import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

@Injectable()
export class RequestsService {

  constructor(private http:HttpClient) {
  }

  /** 获取数据 */
  public getData(url):Observable<any> {
    let thiUrl = url;
    return this.http.get(thiUrl)
      .map(res => res);
  }

  /** 有条件的获取数据 */
  public postData(url, data):Observable<any> {
    let thiUrl = url;
    let thisData = data || '';
    return this.http.get(thiUrl, thisData)
      .map(res => res);
  }

  /** 添加数据 */
  public addData(url, data):Observable<any> {
    let thiUrl = url;
    let thisData = data || '';
    return this.http.post(thiUrl, thisData)
      .map(res => res);
  }

  /** 删除数据 */
  public delData(url, data):Observable<any> {
    let thiUrl = url;
    let thisData = data || '';
    return this.http.post(thiUrl, thisData)
      .map(res => res);
  }

  /** 编辑数据 */
  public editData(url, data):Observable<any> {
    let thiUrl = url;
    let thisData = data || '';
    return this.http.get(thiUrl, thisData)
      .map(res => res);
  }

  /** 对错误信息的处理 */
  public httpErrorFun(err) {
    let res;
    let errNum = err['num'];

    if (errNum == 404) {
      res = "请求的地址不存在";
    } else {
      res = "请求出错";
    }

    return res;
  }

}
